package com.tttshaoqi.server.service.impl;

import com.aliyun.oss.OSS;
import com.tttshaoqi.server.service.OssService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OssServiceImpl implements OssService {

    private final OSS oss;
    @Value("${app.oss.bucket}")
    private String bucket;
    @Value("${app.oss.public-domain}")
    private String publicDomain;

    @Override
    public String uploadImage(MultipartFile file) {
        try (InputStream in = file.getInputStream()){
            String ext = StringUtils.getFilenameExtension(file.getOriginalFilename());
            String key = "uploads/" + UUID.randomUUID().toString().replace("-", "") + (ext != null ? "." + ext : "");
            oss.putObject(bucket, key, in);
            return publicDomain + "/" + key;
        } catch (Exception e) {
            throw new RuntimeException("OSS 上传失败: " + e.getMessage(), e);
        }
    }
}


